package cn.gok.jwtdemo.controller;

import cn.gok.jwtdemo.entity.User;
import cn.gok.jwtdemo.service.UserService;
import cn.gok.jwtdemo.util.JWTUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Retention;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: chen fan
 * @since: 2022/11/23 11:14
 * @description:
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/user/login")
    public Map<String,Object> login(String userName,String password) throws JsonProcessingException {
        User user = userService.login(userName, password);
        Map<String,Object> result = new HashMap<>();

        if ( user == null){
            result.put("code","3000");
            result.put("msg","登录失败，请重试");
            return result;
        }

        //创建jwt token
        Map<String, String> payload = new HashMap<>();
        payload.put("id",user.getId().toString());
        payload.put("username",user.getUsername());
        payload.put("roles", new ObjectMapper().writeValueAsString(user.getRoles()));
        String token = JWTUtil.createToken(payload);


        //响应成功结果
        result.put("code","3001");
        result.put("msg","登录成功");
        result.put("token",token);
        return result;
    }


    @RequestMapping("/user/updateUser")
    public Map<String, Object> updateUser(User user, HttpServletRequest request){

        Map<String,Object> result = new HashMap<>();


        //取出jwt Token中的用户id(以前是从session中取出的)
        String token = request.getHeader("token");
        Integer id = JWTUtil.getValue(token, "id", Integer.class);

        user.setId(id);
        userService.updateUser(user);
        result.put("code","200");
        result.put("msg","修改成功");

        return result;
    }
}
